#!/usr/bin/env python

import time
import oauth
import urllib2

from twitter import Api, User

import simplejson, oauth
import cPickle as p
import os 


CONSUMER_KEY = 'ujhkdNSA7YtQ3EqhtCdgA'
CONSUMER_SECRET = 'gWAIjy1O9iHVTkGa8Lb0S91eqQ2PrYGN2jkQEQua8M0'

REQUEST_TOKEN_URL = 'http://twitter.com/oauth/request_token'
ACCESS_TOKEN_URL = 'http://twitter.com/oauth/access_token'
AUTHORIZATION_URL = 'http://twitter.com/oauth/authorize'
SIGNIN_URL = 'http://twitter.com/oauth/authenticate'

def CreateMap(filename,object):
    try:
        f = open(filename,'w')
        p.dump(object,f)
        f.close()
        return True
    except Exception,e:
        return False
    
def LoadMap(filename):
    try:
        f = open(filename)
        obj = p.load(f)
        f.close()
        return obj
    except Exception,e:
        return

class SimpleOAuth(object):
    def __init__(self, consumer_key, consumer_secret, access_token=None):
        self._Consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
        self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
        self._access_token = access_token

    def getAuthorizationURL(self, token, url=AUTHORIZATION_URL):
        req = self._makeOAuthRequest(url, token=token)
        self._signRequest(req)
        return req.to_url()
    
    def getRequestToken(self, url=REQUEST_TOKEN_URL):
        resp = self._FetchUrl(url)
        token = oauth.OAuthToken.from_string(resp)
        return token

    def _makeOAuthRequest(self, url, token=None,parameters=None, http_method="GET"):
        if not token:
            token = self._access_token
        request = oauth.OAuthRequest.from_consumer_and_token(
                            self._Consumer, token=token, 
                            http_url=url, parameters=parameters, 
                            http_method=http_method)
        return request

    def _signRequest(self, req, signature_method=oauth.OAuthSignatureMethod_HMAC_SHA1()):
        req.sign_request(signature_method, self._Consumer, self._access_token)

    def getAccessToken(self, url=ACCESS_TOKEN_URL):
        token = self._FetchUrl(url)
        return oauth.OAuthToken.from_string(token) 
   
    def _FetchUrl(self,
                    url,
                    post_data=None,
                    parameters=None):
        if post_data: http_method = "POST"
        else: http_method = "GET"

        oauth_req = self._makeOAuthRequest(url,http_method=http_method)
        self._signRequest(oauth_req, self._signature_method)

        argStr = ""
        argData = None
        
        if post_data:
            argData = oauth_req.to_postdata()
        else:
            argStr = "?%s" %(oauth_req.to_postdata())

        print "%s%s" %(url, argStr)
        req = urllib2.Request("%s%s" %(url, argStr),argData, {})
    
        handle = urllib2.urlopen(req)
        return handle.read()

    def GetUserInfo(self, url='http://twitter.com/account/verify_credentials.json'):
        '''Get user information from twitter
        
        Returns:
          Returns the twitter.User object
        '''
        json = self._FetchUrl(url)
        data = simplejson.loads(json)
        return User.NewFromJsonDict(data)
    
def main():
    if os.path.exists("access_token") == False:
        if os.path.exists("request_token") == False:
            simpleoauth = SimpleOAuth(CONSUMER_KEY, CONSUMER_SECRET)
            request_token = simpleoauth.getRequestToken()
            authorization_url = simpleoauth.getAuthorizationURL(request_token)
            CreateMap("request_token",request_token)
            print authorization_url
        else:
            request_token = LoadMap("request_token")
            simpleoauth = SimpleOAuth(CONSUMER_KEY, CONSUMER_SECRET, request_token)
            access_token = simpleoauth.getAccessToken() 
            CreateMap("access_token",access_token)
    else:
        access_token = LoadMap("access_token")
        simpleoauth = SimpleOAuth(CONSUMER_KEY, CONSUMER_SECRET,access_token)
        print simpleoauth.GetUserInfo()
    
if __name__=='__main__' :
    main()
